package com.dabai.dbutils.utils.encryption;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * Description : Other
 *
 * @author BAI
 */
public class FileHashUtils {


    /** hash类型 */
    public static final String HASH_TYPE_MD5    = "MD5";
    public static final String HASH_TYPE_SHA1   = "SHA-1";
    public static final String HASH_TYPE_SHA256 = "SHA-256";
    public static final String HASH_TYPE_SHA384 = "SHA-384";
    public static final String HASH_TYPE_SHA512 = "SHA-512";


    /**
     * 得到文件的哈希
     * 计算文件的Hash值
     *
     * @param file     文件
     * @param hashType 哈希类型
     * @return hash：hashType
     */
    public static String getFileHash(File file, String hashType) {
        String value = "";
        try {
        FileInputStream fis = new FileInputStream(file);
            MappedByteBuffer byteBuffer = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest digest = MessageDigest.getInstance(hashType);
            digest.update(byteBuffer);
            BigInteger bigInteger = new BigInteger(1, digest.digest());
            value = bigInteger.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }



    /**
     * 校验文件 的 hash码
     *
     * @param file     文件
     * @param hash     哈希
     * @param hashType 哈希类型
     * @return 校验结果
     */
    public static boolean validFile(File file, String hash,String hashType) {
        return hash.toLowerCase().equals(getFileHash(file,hashType));
    }


}
